package com.longrise.android.byjk.plugins.aboutme;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.FolderConstants;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.ShSwitchView;
import com.longrise.android.byjk.widget.view.ShSwitchView.OnSwitchStateChangeListener;

import java.io.File;

public class CacheSettingLFView extends BaseActivity implements OnClickListener, OnSwitchStateChangeListener {


    private static final String TAG = "CacheSettingLFView";

    private Toolbar mTitle;

    private TextView mText_Cache;
    private TextView mText_CachePath;
    private TextView mText_CacheDa;
    private TextView mText_LocalCacheSize;

    private ShSwitchView mToggle_3g;
    private ShSwitchView mToggle_WIFI;
    private ShSwitchView mToggle_ClearAutoCache;
    private ShSwitchView mToggle_cache;

    private RelativeLayout mRela_CachePath;
    private RelativeLayout mRela_MaxCacheSize;
    private RelativeLayout mRela_CacheDefinition;
    private RelativeLayout mRela_ClearAllCache;

    private String mCachePath = ""; // 用于存储是 “1本机” 或者“0sd卡”
    private String mCacheDifinitionString = ""; // 用于存储缓存清晰度 "1顺畅" "0为高清"

    private String mSaveSize;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_cachesetting;
    }

    @Override
    public void initView() {
        mText_Cache = (TextView) findViewById(R.id.text_cachesize);
        mText_CacheDa = (TextView) findViewById(R.id.text_cachdeti);
        mText_CachePath = (TextView) findViewById(R.id.text_cachepath);
        mToggle_3g = (ShSwitchView) findViewById(R.id.toggle_3g);
        //移动网络下缓存 xkj
        mToggle_cache = (ShSwitchView) findViewById(R.id.toggle_mobilecache);
        mToggle_WIFI = (ShSwitchView) findViewById(R.id.toggle_wifi);
        mToggle_ClearAutoCache = (ShSwitchView) findViewById(R.id.toggle_autoclearallcache);
        mRela_CachePath = (RelativeLayout) findViewById(R.id.rela_cachepath);
        mRela_MaxCacheSize = (RelativeLayout) findViewById(R.id.rela_cachemaxsize);
        mRela_ClearAllCache = (RelativeLayout) findViewById(R.id.rela_clearallcacge);
        mRela_CacheDefinition = (RelativeLayout) findViewById(R.id.rela_cachdefinition);
        mText_LocalCacheSize = (TextView) findViewById(R.id.text_localcachesieze);

        regEvent();
        switchData();
        getLoaclCacheSize(new File(FolderConstants.CACHE_DIR));

        initTitle();

        Tracker_Google.getInstance().addGoogleScreenName("缓存设置");
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle("缓存设置");
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 得到本地缓存文件大小
     */
    private void getLoaclCacheSize(final File f) {
        new Thread() {
            public void run() {
                try {
                    long length = FileUtil.getFolderSize(f);
                    mSaveSize = FileUtil.FormetFileSize(length);
                    mText_LocalCacheSize.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mSaveSize != null) {
                                mText_LocalCacheSize.setText(mSaveSize.equals("0B") ? "0M" : mSaveSize);
                            } else {
                                mText_LocalCacheSize.setText("0M");
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }.start();
    }

    private void switchData() {
        String cellularnetwork = Control.getCellularNetWork();
        if (cellularnetwork != null && cellularnetwork.equals("1")) {
            mToggle_3g.setOn(true);
        }
        boolean canMobileDownload = Control.isCanMobileDownload();
        if (canMobileDownload) {
            mToggle_cache.setOn(true);
        }
        String wifiautocache = Control.getWifiIsAutoCache();
        if (wifiautocache != null && wifiautocache.equals("1")) {
            mToggle_WIFI.setOn(true);
        }
        String studydoneclear = Control.getStudyVideoDone();
        if (studydoneclear != null && studydoneclear.equals("1")) {
            mToggle_ClearAutoCache.setOn(true);
        }
        String cachemaxsize = Control.getCacheMaxSize();
        if (cachemaxsize != null) {
            mText_Cache.setText(cachemaxsize + "M");
        } else {
            Control.setCacheMaxSize("1024");
            mText_Cache.setText("1024M");
        }

        String cachepath = Control.getCachePath();
        if (cachepath != null) {
            if (cachepath.equals("1")) {
                mText_CachePath.setText("本机");
            } else {
                mText_CachePath.setText("SD卡");
            }
        }
        String cachedefinition = Control.getDeifinition();
        if (cachedefinition != null) {
            if (cachedefinition.equals("1")) {
                mText_CacheDa.setText("顺畅");
            } else {
                mText_CacheDa.setText("高清");
            }
        } else {
            Control.setDeifinition("1");
            mText_CacheDa.setText("顺畅");
        }
    }

    private void regEvent() {
        if (mToggle_3g != null) {
            mToggle_3g.setOnSwitchStateChangeListener(this);
        }

        if (mToggle_cache != null) {
            mToggle_cache.setOnSwitchStateChangeListener(this);
        }
        if (mToggle_WIFI != null) {
            mToggle_WIFI.setOnSwitchStateChangeListener(this);
        }
        if (mToggle_ClearAutoCache != null) {
            mToggle_ClearAutoCache.setOnSwitchStateChangeListener(this);
        }
        if (mRela_CachePath != null) {
            mRela_CachePath.setOnClickListener(this);
        }
        if (mRela_MaxCacheSize != null) {
            mRela_MaxCacheSize.setOnClickListener(this);
        }
        if (mRela_ClearAllCache != null) {
            mRela_ClearAllCache.setOnClickListener(this);
        }
        if (mRela_CacheDefinition != null) {
            mRela_CacheDefinition.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View arg0) {
        int id = arg0.getId();
        if (id == R.id.rela_cachepath) {
            setCachePath();
        } else if (id == R.id.rela_cachemaxsize) {
            setMaxCacheSize();
        } else if (id == R.id.rela_clearallcacge) {
            clearCacheAll();
        } else if (id == R.id.rela_cachdefinition) {
            cacheDefinition();
        }
    }

    /**
     * 设定缓存路径
     * <p/>
     * 待优化 重构
     */
    private void setCachePath() {
        View view = View.inflate(this, R.layout.dialog_cachepath, null);
        final CheckBox checkBoxBJBox = (CheckBox) view.findViewById(R.id.check_bj);
        final CheckBox checkBoxSDBox = (CheckBox) view.findViewById(R.id.check_sd);
        final FrameLayout mRela1 = (FrameLayout) view.findViewById(R.id.rela_item1);
        final FrameLayout mRela2 = (FrameLayout) view.findViewById(R.id.rela_item2);
        TextView text_Cancle = (TextView) view.findViewById(R.id.text_cancle);
        TextView text_Confirm = (TextView) view.findViewById(R.id.text_confirm);
        String cachepath = Control.getCachePath();
        if (cachepath != null) {
            if (cachepath.equals("1")) {
                checkBoxBJBox.setChecked(true);
                checkBoxBJBox.setBackgroundResource(R.drawable.icon_checked);
            } else if (cachepath.equals("0")) {
                checkBoxSDBox.setChecked(true);
                checkBoxSDBox.setBackgroundResource(R.drawable.icon_checked);
            }
        }
        final View.OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                int id = arg0.getId();
                switch (id) {
                    case R.id.text_cancle:
                        DialogUtil.getInstance().dismiss();
                        break;

                    case R.id.text_confirm:
                        if (defalutStatusCachePath(checkBoxBJBox.isChecked(), checkBoxSDBox.isChecked())) {
                            DZZWTools.showToast(CacheSettingLFView.this, "请选择缓存路径", 2 * 1000);
                            return;
                        }
                        Control.setCachePath(mCachePath);
                        if (mCachePath.equals("1")) {
                            mText_CachePath.setText("本机");
                        } else {
                            mText_CachePath.setText("SD卡");
                        }
                        DialogUtil.getInstance().dismiss();
                        break;

                    case R.id.check_bj:

                    case R.id.rela_item1:
                        if (checkBoxBJBox.isChecked()) {
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxBJBox.setChecked(false);
                            mCachePath = "0";
                        } else {
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_checked);
                            checkBoxBJBox.setChecked(true);
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxSDBox.setChecked(false);
                            mCachePath = "1";
                        }
                        break;

                    case R.id.check_sd:

                    case R.id.rela_item2:
                        if (checkBoxSDBox.isChecked()) {
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxSDBox.setChecked(false);
                            mCachePath = "1";
                        } else {
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_checked);
                            checkBoxSDBox.setChecked(true);
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxBJBox.setChecked(false);
                            mCachePath = "0";
                        }
                        break;

                    default:
                        break;
                }
            }
        };
        text_Cancle.setOnClickListener(listener);
        text_Confirm.setOnClickListener(listener);
        mRela1.setOnClickListener(listener);
        mRela2.setOnClickListener(listener);
        DialogUtil.getInstance().creatAlertDialog(this, view, 266, 192);
    }

    /**
     * 设定最大缓存空间
     */
    private void setMaxCacheSize() {
        View v = View.inflate(this, R.layout.dialog_maxcachesize, null);
        final EditText edit_maxSize = (EditText) v.findViewById(R.id.edit_maxcache);
        TextView text_Cancle = (TextView) v.findViewById(R.id.text_cancle);
        TextView text_Confirm = (TextView) v.findViewById(R.id.text_confirm);
        String cacheString = Control.getCacheMaxSize();
        if (cacheString != null) {
            edit_maxSize.setText(cacheString);
            try {
                int posi = cacheString.length();
                edit_maxSize.setSelection(posi);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        text_Cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                DialogUtil.getInstance().dismiss();
            }
        });
        text_Confirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String maxSize = edit_maxSize.getText().toString().trim();
                if (maxSize.equals("")) {
                    DZZWTools.showToast(CacheSettingLFView.this, "请输入您要设定的最大缓存空间", 2 * 1000);
                    return;
                }
                int value = Integer.parseInt(maxSize);
                if (value <= 0) {
                    DZZWTools.showToast(CacheSettingLFView.this, "缓存空间不可小于0M", 2 * 1000);
                    return;
                }
                try {
                    //不考虑小数部分
                    long avilable = FileUtil.getSystemAvailableSDCradSize() / (1024 * 1024); //M
                    PrintLog.e(TAG, "avilable：" + avilable);
                    if (value >= avilable) {
                        DZZWTools.showToast(CacheSettingLFView.this, "已超过手机剩余存储空间" + avilable + "MB", Toast.LENGTH_SHORT);
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Control.setCacheMaxSize(maxSize);
                mText_Cache.setText(maxSize + "M");
                DialogUtil.getInstance().dismiss();
            }
        });
        DialogUtil.getInstance().creatAlertDialog(this, v, 266, 159);
    }

    /**
     * 清空全部缓存
     * 传递文件路径
     */
    private void clearCacheAll() {
        if (mText_LocalCacheSize.getText().equals("0M")) {
            DZZWTools.showToast(this, "已经很干净了", 1000 * 2);
            return;
        }
        View v = View.inflate(this, R.layout.dialog_clearcache, null);
        TextView text_Cancle = (TextView) v.findViewById(R.id.text_cancle);
        TextView text_Confirm = (TextView) v.findViewById(R.id.text_confirm);
        final OnClickListener onClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.text_cancle) {

                } else if (v.getId() == R.id.text_confirm) {
                    File f = new File(FolderConstants.CACHE_DIR);
                    FileUtil.clearFolder(f);
                    DZZWTools.showToast(CacheSettingLFView.this, "清除完毕", 1000 * 2);

                }
                DialogUtil.getInstance().dismiss();
                getLoaclCacheSize(new File(FolderConstants.CACHE_DIR));
            }
        };
        text_Cancle.setOnClickListener(onClickListener);
        text_Confirm.setOnClickListener(onClickListener);
        DialogUtil.getInstance().creatAlertDialog(this, v, 266, 171);
    }

    /**
     * 设定缓存清晰度
     */
    private void cacheDefinition() { // 1为顺畅 0为高清
        View view = View.inflate(this, R.layout.dialog_cachedati, null);
        final CheckBox checkBoxBJBox = (CheckBox) view.findViewById(R.id.check_mdpi);
        final CheckBox checkBoxSDBox = (CheckBox) view.findViewById(R.id.check_hdpi);
        TextView text_Cancle = (TextView) view.findViewById(R.id.text_cancle);
        TextView text_Confirm = (TextView) view.findViewById(R.id.text_confirm);
        final RelativeLayout rela_Dpi1 = (RelativeLayout) view.findViewById(R.id.rela_itemdpi1);
        final RelativeLayout rela_Dpi2 = (RelativeLayout) view.findViewById(R.id.rela_itemdpi2);
        String cachedefinition = Control.getDeifinition();
        PrintLog.e(TAG, "cacheDefinition：" + cachedefinition);
        if (!TextUtils.isEmpty(cachedefinition)) {
            if (cachedefinition.equals("1")) {
                checkBoxBJBox.setChecked(true);
                checkBoxBJBox.setBackgroundResource(R.drawable.icon_checked);
            } else if (cachedefinition.equals("0")) {
                checkBoxSDBox.setChecked(true);
                checkBoxSDBox.setBackgroundResource(R.drawable.icon_checked);
            }
        }
        final View.OnClickListener listener = new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                int id = arg0.getId();
                switch (id) {
                    case R.id.text_cancle:
                        DialogUtil.getInstance().dismiss();
                        break;

                    case R.id.text_confirm:
                        if (defalutStatusCacheDetifition(checkBoxBJBox.isChecked(), checkBoxSDBox.isChecked())) {
                            DZZWTools.showToast(CacheSettingLFView.this, "请选择缓存类型", 2 * 1000);
                            return;
                        }
                        Control.setDeifinition(mCacheDifinitionString);
                        if (mCacheDifinitionString.equals("1")) {
                            mText_CacheDa.setText("顺畅");
                        } else if (mCacheDifinitionString.equals("0")) {
                            mText_CacheDa.setText("高清");
                        }
                        DialogUtil.getInstance().dismiss();
                        break;

                    case R.id.check_mdpi:

                    case R.id.rela_itemdpi1:
                        if (checkBoxBJBox.isChecked()) {
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxBJBox.setChecked(false);
                            mCacheDifinitionString = "0";
                        } else {
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_checked);
                            checkBoxBJBox.setChecked(true);
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxSDBox.setChecked(false);
                            mCacheDifinitionString = "1";
                        }
                        break;

                    case R.id.check_hdpi:

                    case R.id.rela_itemdpi2:
                        if (checkBoxSDBox.isChecked()) {
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxSDBox.setChecked(false);
                            mCacheDifinitionString = "1";
                        } else {
                            checkBoxSDBox.setBackgroundResource(R.drawable.icon_checked);
                            checkBoxSDBox.setChecked(true);
                            checkBoxBJBox.setBackgroundResource(R.drawable.icon_uncheck);
                            checkBoxBJBox.setChecked(false);
                            mCacheDifinitionString = "0";
                        }
                        break;

                    default:
                        break;
                }
            }
        };
        text_Cancle.setOnClickListener(listener);
        text_Confirm.setOnClickListener(listener);
        rela_Dpi1.setOnClickListener(listener);
        rela_Dpi2.setOnClickListener(listener);
        DialogUtil.getInstance().creatAlertDialog(this, view, 266, 192);
    }

    /**
     * 默认缓存路径为本机
     */
    private boolean defalutStatusCachePath(boolean b, boolean b_) {
        boolean bool = false;
        if (!b && !b_) {
            Control.setCachePath("1");
            mCachePath = "1";
            bool = true;
        }
        return bool;
    }

    /**
     * 默认缓存清晰度为顺畅
     **/
    private boolean defalutStatusCacheDetifition(boolean b, boolean b_) {
        boolean bool = false;
        if (!b && !b_) {
            Control.setDeifinition("1");
            mCacheDifinitionString = "1";
            bool = true;
        }
        return bool;
    }

    /**
     * @see
     */
    @Override
    public void onSwitchStateChange(View v, boolean isOn) {
        int id = v.getId();
        if (id == R.id.toggle_3g) {
            if (isOn) {
                Control.setCellularNetWork("1"); //是否允许移动网络下播放
            } else {
                Control.setCellularNetWork("0");
            }
        }
        if (id == R.id.toggle_mobilecache) { //移动网络下载
            Control.setIsCanMobileDownload(isOn);
        }
        if (id == R.id.toggle_wifi) {
            if (isOn) {
                Control.setWifiIsAutoCache("1");

            } else {
                Control.setWifiIsAutoCache("0");
            }
        }
        if (id == R.id.toggle_autoclearallcache) {
            if (isOn) {
                Control.setStudyVideoDone("1");
            } else {
                Control.setStudyVideoDone("0");
            }
        }
    }
}
